import axios from 'axios';
import { Loading, Message } from 'element-ui';
import router from '../router/index.js';

var loading;
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0,0,0,0.7)'
    });
}
function endLoading(){
    startLoading(),
    loading.close();
}


// 请求拦截
var baseUrl = "";
axios.defaults.baseURL = baseUrl;
// 设置请求响应时间
axios.defaults.timeout = 10000;
// 设置请求头
axios.interceptors.request.use(
    (confing) => {
        startLoading();
        confing.headers.Accept = "application/json,text/json,text/javascript,text/html,text/plain";
        // if (localStorage.eToken) {
        //     confing.headers.Authorization = localStorage.eToken
        // }
        return confing;
    },
    (error) => {
        return Promise.reject(error);
    }
);
//响应拦截
axios.interceptors.response.use(
    (response) => {
        // const status = response.data.status;
        endLoading();
        return response.data;
    },(error) => {
        endLoading();
        console.log(error);
        Message.error(error.response.data);
        // 获取状态码
        const { status } = error.response;
        if(status){
            switch (status) {
                case 401:
                // 未登录
                    Message.error('请重新登录');
                    //清楚token
                    // localStorage.removeItem('eToken');
                    //跳转到登录页面
                    router.push('/');
                    break;
                case 403:
                // 登录过期对用户进行提示 token过期
                // 清除本地token和清空vuex中token对象
                // 跳转登录页面
                    break;
                default:
                    Message.error(error.response.data.message);
            }
            return error.response
        }
        if (status === 401) {

        }
        if(status == 404){
            Message.error('请求出错!');
        }
        return Promise.reject(error);
    }
);
export default axios;
